package com.lumlord.common.executeTime;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.method.HandlerMethod;

import com.lumlord.common.domain.log.monitor.InterfaceInfo;
import com.lumlord.common.exception.BusinessException;
import com.lumlord.common.shiro.config.JwtAuthFilter;
import com.lumlord.util.JdbcTemplateUtils;

/**
 * @description:
 * @author: GPF
 * @create 2019年9月9日 17:44:24
 */
@Aspect
@Component
public class ApiExecuteTime {
	private static Logger logger = LoggerFactory.getLogger(ApiExecuteTime.class);

	@Pointcut("@annotation(com.lumlord.common.annotation.Api)")
	public void apiPointCut() {

	}

	@Around("apiPointCut()")
	public Object around(ProceedingJoinPoint point) throws Throwable {
		// 开始时间
		long start = System.currentTimeMillis();
		// 执行方法
		Object result = point.proceed();
		long end = System.currentTimeMillis();
		// 请求的方法名
		// logger.info("【接口执行时间】接口名：{}.{},执行时间:{}毫秒",className,methodName,(end-start));
		if(null != request){
			try {
				request.setAttribute("executeTime", (end - start));
				request.setAttribute("design", getDesign(point));
			}catch (Throwable e){}
		}
		return result;// Result.success(result).put("cost", (end-start)).put("className",
						// className).put("methodName", methodName);
	}

	private String getDesign(ProceedingJoinPoint point) throws BusinessException {
		ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
				.getRequestAttributes();
		HttpServletRequest request = requestAttributes.getRequest();
		HttpServletResponse response = requestAttributes.getResponse();
		HandlerMethod handlerMethod = jwtAuthFilter.getMethod(request, response);
		if (handlerMethod != null) {
			String clazz = handlerMethod.getMethod().toString();
			InterfaceInfo info = new InterfaceInfo();
			info.setClazz(clazz);
			Object o = jdbcTemplateUtils.queryOne(info);
			if (null != o) {
				InterfaceInfo i = (InterfaceInfo) o;
				return i.getDesign();
			}
		}
		return null;
	}

	@Autowired
	private JwtAuthFilter jwtAuthFilter;

	@Autowired
	private JdbcTemplateUtils jdbcTemplateUtils;

	@Autowired
	private HttpServletRequest request; // 自动注入request
}
